<!--
 * @Author: 尹艳婷
 * @Date: 2022-05-30
 * @Description: 大卡片-用户自定义
 * @FilePath: \code\ctp-static-portal-front\src\components\Magnet\components\card-custom.vue
-->
<template>
  <div
    :id="swiperId"
    class="swiper-container"
    :style="{
      width: contentWidth + 'px'
    }"
  >
    <div
      class="swiper-wrapper clear_fix"
      :style="{
        width: contentWidth * sliderMagnetArr.length + 'px'
      }"
    >
      <div
        class="swiper-slide custom-slide clear_fix"
        :style="{
          width: contentWidth + 'px'
        }"
        v-for="(slideritem, sliderIndex) in sliderMagnetArr"
        :key="sliderIndex"
      >
        <div class="comBoxSlider" v-for="(eachItem, eachIndex) in slideritem" :key="eachIndex">
          <div
            class="big-magnet item-card"
            @click="doSomething(eachItem)"
            :style="{
              width: eachWidth + 'px',
              backgroundColor: eachItem.bgColor
                ? eachItem.bgColor
                : magnetStyle.iconBackGroundColor,
              borderRadius: magnetStyle.borderRadius == 0 ? 0 : magnetStyle.borderRadius + 'px'
            }"
            v-if="!(eachItem instanceof Array)"
          >
            <div class="card-detail">
              <div class="magnet-icon">
                <img
                  :src="eachItem.imageLayouts[0].imageUrl"
                  :style="{
                    width: 'inherit',
                    height: 'inherit'
                  }"
                  alt=""
                  srcset=""
                  v-if="isImg(eachItem)"
                />
                <i
                  v-else
                  class="vportal"
                  :class="
                    eachItem.imageLayouts[0].imageUrl &&
                    eachItem.imageLayouts[0].imageUrl.includes('vp-')
                      ? eachItem.imageLayouts[0].imageUrl
                      : `vp-${eachItem.imageLayouts[0].imageUrl
                          .replace(/\..*$/, '')
                          .replace(/^.*\_/, '')}`
                  "
                  :style="{
                    color: eachItem.iconColor
                  }"
                ></i>
              </div>
              <div class="magnet-name" :class="`align_${magnetStyle.textAlign}`">
                <span
                  :class="doubleFontEllipsis"
                  :style="{
                    color: eachItem.fontColor
                  }"
                  >{{ eachItem.displayName }}</span
                >
              </div>
            </div>
          </div>
          <div class="box2" v-else>
            <div
              class="small-magnet item-card"
              @click="doSomething(smallItem)"
              :style="{
                width: eachWidth + 'px',
                backgroundColor: smallItem.bgColor
                  ? smallItem.bgColor
                  : magnetStyle.iconBackGroundColor,
                borderRadius: magnetStyle.borderRadius == 0 ? 0 : magnetStyle.borderRadius + 'px'
              }"
              v-for="(smallItem, smallIndex) in eachItem"
              :key="smallIndex"
            >
              <div class="card-detail">
                <div class="magnet-icon">
                  <img
                    :src="smallItem.imageLayouts[0].imageUrl"
                    :style="{
                      width: 'inherit',
                      height: 'inherit'
                    }"
                    alt=""
                    srcset=""
                    v-if="isImg(smallItem)"
                  />
                  <i
                    v-else
                    class="vportal"
                    :class="
                      smallItem.imageLayouts[0].imageUrl &&
                      smallItem.imageLayouts[0].imageUrl.includes('vp-')
                        ? smallItem.imageLayouts[0].imageUrl
                        : `vp-${smallItem.imageLayouts[0].imageUrl
                            .replace(/\..*$/, '')
                            .replace(/^.*\_/, '')}`
                    "
                    :style="{
                      color: smallItem.iconColor
                    }"
                  ></i>
                </div>
                <div class="magnet-name" :class="`align_${magnetStyle.textAlign}`">
                  <span
                    :class="doubleFontEllipsis"
                    :style="{
                      color: smallItem.fontColor
                    }"
                    >{{ smallItem.displayName }}</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 分页器 -->
    <div
      class="pagination"
      :style="{
        display: sliderMagnetArr.length > 1 ? 'block' : 'none'
      }"
    ></div>
    <!-- 前一个 -->
    <div
      class="control-btn left-btn"
      @click="handleLeft"
      :style="{
        display: sliderMagnetArr.length > 1 ? 'block' : 'none'
      }"
    >
      <span>&lt;</span>
    </div>
    <!-- 后一个 -->
    <div
      class="control-btn right-btn"
      @click="handleRight"
      :style="{
        display: sliderMagnetArr.length > 1 ? 'block' : 'none'
      }"
    >
      <span> &gt;</span>
    </div>
  </div>
</template>

<script>
  import swiper from '@/mixins/swiper';
  export default {
    name: 'CardCustom',
    mixins: [swiper],
    props: {
      contentWidth: {
        type: Number,
        default: 1400
      },
      magnetStyle: {
        type: Object
      },
      magnet: {
        type: Array
      },
      isImg: {
        type: Function
      },
      doSomething: {
        type: Function
      },
      swiperId: {
        type: String
      }
    },
    data() {
      return {
        // 磁贴最终宽度，默认为205
        eachWidth: 205,

        // 深拷贝一份magnet数组
        magnetCopy: [],
        // 每个slider中磁贴数组组合成的数组
        sliderMagnetArr: [],
        // 栏目支持的列数中会出现多少个完整组合
        sliderGroupsNum: 1,
        // 二维数组，每个slider磁贴数为第一层数组，第二层数组是每个slider中的完整组合
        magnetArr: [],
        // 表示每个用户自定义完整组合的索引号
        magnetIndexArr: []
      };
    },
    computed: {
      // customSliderNum() {
      //     console.log(this.sliderNum,'this.sliderNum');
      //     let n = Math.ceil(this.magnet.length / this.sliderNum);
      //     return new Array(n).fill('1').map((v, i) => i);
      // },

      doubleFontEllipsis() {
        return this.magnetStyle.propertyMap.wordWrap == 'double' ? 'font-ellipsis2' : '';
      }
    },
    created() {
      this.magnetCopy = [...this.magnet];
      this.initCustom();
      console.log(this.sliderMagnetArr, 'this.sliderMagnetArr');
    },
    mounted() {
      // this.initCustom();
      this.initSwiperCustom();

      this.initEllipsis2();
      this.verticalAlign('.magnet-name');
    },
    methods: {
      // 自定义磁贴
      initCustom() {
        // 用户设置的大卡片数
        let bNum = Number(this.magnetStyle.bigNum);
        // 用户设置的小卡片数
        let sNum = Number(this.magnetStyle.smallNum);
        // 每个磁贴宽度
        let itemWidth = 205;
        // 每个磁贴的右间距
        let itemMarginRight = 20;
        // 计算栏目宽度能展示多少个磁贴（每个slider能展示多少个），最多支持列数
        let colNum = parseInt(this.contentWidth / (itemWidth + itemMarginRight));

        /**最多6列  避免高分辨率列太多   视觉效果不行**/
        // if (colNum > 6) {
        //     colNum = 6;
        // }

        // 计算每个磁贴还可以增加多少宽度
        let dynamicValue = parseInt(
          (this.contentWidth - colNum * (itemWidth + itemMarginRight)) / colNum
        );
        itemWidth += dynamicValue;
        // 磁贴最终宽度
        this.eachWidth = itemWidth;
        // 通过大磁贴数和小磁贴数计算每组磁贴列数
        let groupNum = bNum - 0 + sNum / 2;

        // 用户自定义列数小于栏目能支持列数时每个是slider中能展示的磁贴个数
        let sn = colNum;
        if (groupNum < colNum) {
          let groupMagNum = 2 * groupNum - bNum;
          let exceptNum = parseInt(colNum / groupNum);
          let remainNum =
            colNum % groupNum <= bNum ? colNum % groupNum : 2 * (colNum % groupNum) - bNum;

          sn = groupMagNum * exceptNum + remainNum;
        }
        // 计算每个slider中能展示磁贴多少个
        let magnetNum = groupNum >= colNum ? (bNum >= colNum ? colNum : 2 * colNum - bNum) : sn;
        // 第一层
        while (this.magnetCopy.length) {
          this.sliderMagnetArr.push(this.magnetCopy.splice(0, magnetNum));
        }
        // 第二层
        // 小卡片的第一个索引号数组
        let smallCardIndex = [];
        if (groupNum >= colNum) {
          for (let i = bNum; i < magnetNum; i += 2) {
            smallCardIndex.push(i);
          }
        } else {
          let ceilNum = Math.ceil(colNum / groupNum);
          for (let i = 0; i < ceilNum; i++) {
            for (
              let j = bNum + (groupNum * 2 - bNum) * i;
              j < (groupNum * 2 - bNum) * (i + 1);
              j += 2
            ) {
              if (j >= this.sliderMagnetArr[0].length - 1) {
                break;
              }
              smallCardIndex.push(j);
            }
          }
        }
        console.log(smallCardIndex, 'smallCardIndex');
        let sliderArrCopy = [];
        this.sliderMagnetArr.forEach((item) => {
          sliderArrCopy.push([...item]);
        });
        for (let m = 0; m < this.sliderMagnetArr.length; m++) {
          for (let k = 0; k < smallCardIndex.length; k++) {
            if (this.sliderMagnetArr[m][k]) {
              let item = sliderArrCopy[m].slice(smallCardIndex[k], smallCardIndex[k] + 2);
              this.sliderMagnetArr[m].splice(smallCardIndex[k] - k, 2, item);
            }
          }
        }
      },

      // 轮播
      initSwiperCustom() {
        this.setSwiper(
          new Swiper(`#${this.swiperId}`, {
            mode: 'horizontal',
            pagination: `#${this.swiperId}>.pagination`,
            paginationClickable: true,
            createPagination: true,
            centeredSlides: true,
            offsetPxBefore: 100
            // offsetPxAfter: 100,
          })
        );
      },

      handleLeft() {
        this._swiper.swipePrev();
      },

      handleRight() {
        this._swiper.swipeNext();
      },
      isIE() {
        var ua = window.navigator.userAgent;

        if (ua.indexOf('MSIE ') >= 0) {
          return true;
        } else {
          return ua.indexOf('Trident/') >= 0;
        }
      },
      verticalAlign(ele, isFirst) {
        ele = $(this.$el).find(ele);
        setTimeout(function () {
          $.each($(ele), function (index, item) {
            if ($(item).hasClass('is-verticalAlign')) {
              return true;
            }
            var eleHeight = $(item).height();
            var childDomHeight = 0;
            $.each($(item).children(), function (childIndex, child) {
              childDomHeight += $(child).height();
              if (isFirst) {
                return false;
              }
            });

            var paddingVer = parseInt((eleHeight - childDomHeight) / 2);
            $(item).css({
              'padding-top': paddingVer + 'px',
              'padding-bottom': paddingVer + 'px',
              'box-sizing': 'border-box'
            });
            $(item).addClass('is-verticalAlign');
          });
        }, 0);
      },
      initEllipsis2() {
        if (this.isIE()) {
          var ele = $(this.$el).find('.font-ellipsis2');
          // 汉字
          var cnPattern = /[\u4E00-\u9FA5]/;
          setTimeout(function () {
            $.each($(ele), function (index, item) {
              var _fontSize = $(item).css('fontSize');
              var _width = $(item).width();
              var _len = Math.floor((_width * 2) / parseInt(_fontSize));
              var text = $(item)
                .text()
                .replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
              var textLen = 0;
              var curLen = 0;
              $.each(text, function (i, str) {
                if (cnPattern.test(str)) {
                  textLen += 1;
                } else {
                  textLen += 0.5;
                }
                if (_len < textLen) {
                  curLen = i - 1;
                  return false;
                }
              });

              if (_len < textLen) {
                var ellipsis2Text = $(item)
                  .text()
                  .substring(0, curLen - 2);
                $(item).text(ellipsis2Text + '...');
              }
            });
          }, 0);
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  // 轮播
  .swiper-container {
    height: 370px;
  }

  .swiper-container:hover {
    .control-btn {
      display: block;
    }
  }

  .pagination {
    position: absolute;
    bottom: 0;
    z-index: 20;
    // bottom: 10px;
    width: 100%;
    height: 30px;
    text-align: center;
  }

  /deep/.swiper-active-switch {
    width: 10px;
  }

  .control-btn {
    position: absolute;
    top: 50%;
    z-index: 10;
    display: none;
    width: 50px;
    height: 50px;
    margin-top: -25px;
    font-size: 22px;
    line-height: 50px;
    color: #fff;
    text-align: center;
    cursor: pointer;
    background-color: rgba(0, 0, 0, 0.15);
    border-radius: 50%;
  }

  .left-btn {
    left: 30px;
  }

  .right-btn {
    right: 30px;
  }
  // 大卡片
  .custom-slide {
    overflow-x: auto;
    overflow-y: hidden;

    .comBoxSlider {
      float: left;
    }

    .box2 {
      height: 300px;
    }

    .box2 .small-magnet:first-child {
      margin-bottom: 20px;
    }

    .item-card {
      position: relative;
      margin-right: 20px;
      cursor: pointer;

      .card-detail {
        text-align: center;

        .magnet-icon {
          display: inline-block;
          width: 42px;
          height: 42px;
          overflow: hidden;
          font-size: 42px;
          color: #fff;
          text-align: center;

          i {
            display: block;
            color: #fff;
          }
        }

        .magnet-name {
          height: 40px;
          margin: 0 10px;
          overflow: hidden;
          font-size: 16px;
          // line-height: 40px;
          line-height: 1.2;
          text-align: center;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .magnet-name.align_left,
        .magnet-name.align_right {
          position: absolute;
          right: 0;
          bottom: 10px;
          left: 0;
          margin-top: 0 !important;
        }

        .align_left {
          text-align: left;
        }

        .align_right {
          text-align: right;
        }
      }
    }

    .big-magnet {
      height: 300px;
      padding-top: 107px;
      box-sizing: border-box;
    }

    .small-magnet {
      height: 140px;
      padding-top: 27px;
      box-sizing: border-box;
    }
  }

  .clear_fix::after {
    display: block;
    height: 0;
    overflow: hidden;
    clear: both;
    content: '.';
    visibility: hidden;
  }

  .clear_fix {
    zoom: 1;
  }

  .font-ellipsis2 {
    position: relative;
    display: block;
    display: -webkit-box !important;
    overflow: hidden;
    line-height: 1.2 !important;
    text-overflow: inherit !important;
    word-break: break-all;
    white-space: normal !important;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
</style>
